package com.jindy.module.oaFinanceApproval.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jindy.activiti.service.IProcessService;
import com.jindy.common.constant.Constants;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.common.utils.StringUtils;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalRecord.domain.ApprovalRecord;
import com.jindy.module.approvalRecord.mapper.ApprovalRecordMapper;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.oaDepartApproval.domain.SyOaDepart;
import com.jindy.module.oaDepartApproval.service.impl.SyOaDepartServiceImpl;
import com.jindy.module.oacopy.service.ISyOaCopyService;
import com.jindy.module.oacopyconfig.domain.SyOaCopyConfig;
import com.jindy.module.oacopyconfig.mapper.SyOaCopyConfigMapper;
import com.jindy.module.serialNum.service.ISySerialNumTService;
import com.jindy.module.syTableRecord.service.ISyTableRecordTService;
import com.jindy.system.domain.SysUserRoleDeptInfo;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jindy.module.oaFinanceApproval.mapper.SyOaFinanceMapper;
import com.jindy.module.oaFinanceApproval.domain.SyOaFinance;
import com.jindy.module.oaFinanceApproval.service.ISyOaFinanceService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 财务资金调拨审批Service业务层处理
 * 
 * @author jindy
 * @date 2023-06-21
 */
@Service
public class SyOaFinanceServiceImpl implements ISyOaFinanceService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SyOaFinanceServiceImpl.class);

    @Autowired
    private SyOaFinanceMapper syOaFinanceMapper;

    @Autowired
    private IProcessService processService;

    /**
     * 抄送Service
     */
    @Resource
    private ISyOaCopyService syOaCopyService;

    /**
     * 配置表
     */
    @Resource
    private SyOaCopyConfigMapper syOaCopyConfigMapper;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ISySerialNumTService serialNumTService;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 用户Service
     */
    @Resource
    private ISysUserService sysUserService;

    /**
     * 设备Mapper
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 存储表Service
     */
    @Resource
    private ISyTableRecordTService iSyTableRecordTService;

    /**
     * 查询财务资金调拨审批
     * 
     * @param id 财务资金调拨审批主键
     * @return 财务资金调拨审批
     */
    @Override
    public SyOaFinance selectSyOaFinanceById(Long id)
    {
        return syOaFinanceMapper.selectSyOaFinanceById(id);
    }

    /**
     * 查询财务资金调拨审批列表
     * 
     * @param syOaFinance 财务资金调拨审批
     * @return 财务资金调拨审批
     */
    @Override
    public List<SyOaFinance> selectSyOaFinanceList(SyOaFinance syOaFinance)
    {
        if (!SecurityUtils.isAdmin(SecurityUtils.getLoginUser().getUser().getUserId())) {
            syOaFinance.setCreateBy(SecurityUtils.getUsername());
        }
        List<SyOaFinance> list = syOaFinanceMapper.selectSyOaFinanceList(syOaFinance);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
//        return syOaFinanceMapper.selectSyOaFinanceList(syOaFinance);
    }

    /**
     * 新增财务资金调拨审批
     * 
     * @param syOaFinance 财务资金调拨审批
     * @return 结果
     */
    @Override
    public int insertSyOaFinance(SyOaFinance syOaFinance)
    {
        // 生成流水单号
        String serialNum = serialNumTService.generateSerialNum("CWZJDBSP");
        if (StringUtils.isBlank(serialNum)) {
            throw new BaseException("新增财务资金调拨审批-获取财务资金调拨单号失败");
        }
        //获取离职人信息
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        syOaFinance.setApplyUserId(userId.toString());
        syOaFinance.setApplyUserName(SecurityUtils.getLoginUser().getUser().getUserName());

        //获取申请时间
        syOaFinance.setApplyTime(DateUtils.getNowDate());

        syOaFinance.setSerialNum(serialNum);
        syOaFinance.setBusinessStatus(Constants.DRAFT);
        syOaFinance.setCreateTime(DateUtils.getNowDate());
        iSyTableRecordTService.saveEntityAndTable(syOaFinance,serialNum);
        return syOaFinanceMapper.insertSyOaFinance(syOaFinance);
//        syOaFinance.setCreateTime(DateUtils.getNowDate());
//        return syOaFinanceMapper.insertSyOaFinance(syOaFinance);
    }

    /**
     * 修改财务资金调拨审批
     * 
     * @param syOaFinance 财务资金调拨审批
     * @return 结果
     */
    @Override
    public int updateSyOaFinance(SyOaFinance syOaFinance)
    {
        syOaFinance.setUpdateTime(DateUtils.getNowDate());
        return syOaFinanceMapper.updateSyOaFinance(syOaFinance);
    }

    /**
     * 批量删除财务资金调拨审批
     * 
     * @param ids 需要删除的财务资金调拨审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOaFinanceByIds(Long[] ids)
    {
        return syOaFinanceMapper.deleteSyOaFinanceByIds(ids);
    }

    /**
     * 删除财务资金调拨审批信息
     * 
     * @param id 财务资金调拨审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOaFinanceById(Long id)
    {
        return syOaFinanceMapper.deleteSyOaFinanceById(id);
    }

    /**
     * 提交申请
     *
     * @param syOaFinance
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitApply(SyOaFinance syOaFinance) throws Exception {
        // 初始化值
        Map<String, Object> variables = createVariables(syOaFinance);
        // 启动流程
        processService.submitApply(syOaFinance, "finance", variables);
        // 添加抄送人
        syOaCopyService.addCopyUsers("CWZJDBSP", syOaFinance.getId());
        //新增审批记录
        List<Long> longs = addApprovalRecord(syOaFinance, variables);
        // 通知审批人
        sendApproveMessage(longs);
        syOaFinance.setBusinessStatus(Constants.APPROVE);
        updateSyOaFinance(syOaFinance);
    }

    /**
     * 获取审批记录对象
     *
     * @param syOaFinance
     * @return
     */
    private ApprovalRecord getApprovalRecord(SyOaFinance syOaFinance) {
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setSerialNum(syOaFinance.getSerialNum());
        approvalRecord.setUserId(Long.valueOf(syOaFinance.getApplyUserId()));
        approvalRecord.setOrderId(syOaFinance.getId());
        approvalRecord.setUserName(syOaFinance.getApplyUserName());
        approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        approvalRecord.setUpdateBy(syOaFinance.getApplyUserName());
        approvalRecord.setCreateBy(syOaFinance.getApplyUserName());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 新增审批记录
     * @param syOaFinance
     * @param map
     * @return
     */
    private List<Long> addApprovalRecord(SyOaFinance syOaFinance, Map<String, Object> map) {
        List<Long> list = new ArrayList<>();
        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(syOaFinance);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(Long.valueOf(syOaFinance.getApplyUserId()));
        firstApprovalRecord.setApproverName(syOaFinance.getApplyUserName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);

        sequence++;
        //  第一审批人
        ApprovalRecord secondApprovalRecord = getApprovalRecord(syOaFinance);
        secondApprovalRecord.setSequence(sequence);
        secondApprovalRecord.setApprovalStatus(Constants.APPROVE);
        String finleaderId=map.get("finleaderId").toString();
        secondApprovalRecord.setApproverId(Long.parseLong(finleaderId));
        secondApprovalRecord.setApproverName((String) map.get("finleader"));
        approvalRecordMapper.insertApprovalRecord(secondApprovalRecord);
        list.add(Long.parseLong(finleaderId));

        return list;
    }

    /**
     * 逻辑流初始化
     *
     * @param syOaFinance
     * @return
     */
    public Map<String, Object> createVariables(SyOaFinance syOaFinance) {
        Map<String, Object> var = new HashMap<>(500);
        // 判断申请人是否是主管

        //财务经理审批
        SyOaCopyConfig syOaCopyConfig = new SyOaCopyConfig();
        syOaCopyConfig.setNumber("CWZJDBSP_FIN_LEADER");
        List<SyOaCopyConfig> syOaCopyConfigs = syOaCopyConfigMapper.selectSyOaCopyConfigList(syOaCopyConfig);
        if (CollectionUtils.isEmpty(syOaCopyConfigs)) {
            throw new BaseException("createVariables", "财务资金调拨审批获取HR负责人失败");
        }
        var.put("finleader",syOaCopyConfigs.get(0).getCopyUserName());
        var.put("finleaderId",syOaCopyConfigs.get(0).getCopyUserId());

        return var;
    }

    /**
     * 给审批人推送消息
     * @param addJpushList
     */
    private void sendApproveMessage(List<Long> addJpushList) {
        try {
            List<String> addRegIds = jpushMapper.selectRegistrationIdsByUserIds(addJpushList);
            if (!CollectionUtils.isEmpty(addRegIds)){
                UniJpushUtils.sendApproveMessage(addRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("财务资金调拨审批审批人推送通知失败",e);
        }
    }
}
